import UserModel from "../../../../models/User";
import Crypt from "../../../../utils/Crypt";
import Compare from "../../../../utils/Compare";

const userModel = new UserModel()

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    avatarUrl: defaultAvatarUrl,
    nickname: '',
    base64Image: ''
  },
  onLoad: function (options) {

    const ver = wx.getSystemInfoSync().SDKVersion
    if (Compare(ver, '2.10.4') < 0) {
      return wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
    if (Compare(ver, '2.21.2') < 0) {
      return wx.redirectTo({
        url: '/sub_main/pages/user/get-info/index'
      })
    }

    userModel.getInfo({ noCheck: true }).then(response => {
      let { data } = response
      data = Crypt.parse(data)
      this.setData({
        nickname: data.nickname,
        avatarUrl: data.avatar
      })
    })
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      avatarUrl,
    })

    // avatar base64
    const x = 'data:image/jpeg;base64,' + wx.getFileSystemManager().readFileSync(e.detail.avatarUrl,'base64')
    this.setData({
      base64Image: x,
    })

    // console.log(avatarUrl)
  },

  changeNickname(e) {
    const nickname = e.detail.value
    this.setData({
      nickname,
    })

    // console.log(nickname)
  },

  save() {
    const { avatarUrl, nickname, base64Image } = this.data
    // console.log(avatarUrl, nickname)
    userModel.changeAvatar({
      avatarUrl,
      nickname,
      base64Image
    }).then(() => {
      wx.showToast({ title: '操作成功', icon: "none" })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/center/index'
        })
      }, 1000)
    })
  },

  onCancel() {
    wx.switchTab({
      url: '/pages/home/index'
    })
  }

});
